package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojo.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;


    /**
     *  生成静态文件上传到minIO中
     * @param apArticle  需要更新文章静态页面的地址
     * @param content    生成静态页面内容需要
     */
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        try {
            // 获取模版对象
            Template template = configuration.getTemplate("article.ftl");
            // 准备填充数据
            List<Map> list = JSON.parseArray(content, Map.class);
            Map map = new HashMap();
            map.put("content", list);
            // 生成静态页面并存储到minio
            StringWriter stringWriter = new StringWriter();
            template.process(map, stringWriter);
            byte[] bytes = stringWriter.toString().getBytes();
            // 上传HTML页面到minio
            String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", new ByteArrayInputStream(bytes));
            // 将地址更新到article
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
